import axios, { AxiosRequestConfig, AxiosPromise } from 'axios'
import env from 'constants/env.json'
import { getAuthorization } from './authorization'
import { Toast } from 'components';
const httpInit = axios.create({ timeout: 10000 })
export type HttpConfig = AxiosRequestConfig

/**
 * 0000 操作成功
 * 0001 操作失败
 * 0002 账号不存在
 * 0003 密码错误
 * 0004 其它错误
 */

httpInit.interceptors.request.use(async config => {
	const login = getAuthorization()
	if (login.isLogin && login.token) {
		config.headers.Authorization = login.token
	}
	config.url = env.httpBaseUrl + config.url
	console.log('config.url', config.url)
	return config
})
httpInit.interceptors.response.use(
	res => {
		console.log('res', res)
		const body = res.data
		if (body.code && body.code === 200) {
			return res
		} else if (body.code && body.code === 401) {
			Toast.show("登陆已过期，请退出重新登陆！")
		}
		else {
			throw res
		}
	},
	error => {
		console.log('http error', error)
		return Promise.reject(error)
	}
)

export function httpPost<T = any>(url: string, data?: any, config?: HttpConfig): AxiosPromise<T> {
	return httpInit.post(url, data, config)
}
export function httpGet<T = any>(url: string, config?: HttpConfig): AxiosPromise<T> {
	return httpInit.get(url, config)
}
export function httpDelete<T = any>(url: string, config?: HttpConfig): AxiosPromise<T> {
	return httpInit.get(url, config)
}
export function httpPut<T = any>(url: string, data?: any, config?: HttpConfig): AxiosPromise<T> {
	return httpInit.put(url, data, config)
}
export default httpInit
